package com.ysx.detailservice;

import com.ysx.pojo.UserO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;


public class UserDetailServerImpl implements UserDetailsService {
    //    伪造一个数据库
    private static Map<String, UserO> hashMap=new HashMap<>();
    //    创建一个加密器 容器中有 直接使用注入的方式
    private static BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();
    //    静态代码块记载hm数据
    static {
    //        存入第一个对象
        UserO userO = new UserO();
    //        将密码加密
        String pwd = bCryptPasswordEncoder.encode("123456");
        userO.setUsername("admin");
        userO.setPassword(pwd);
        hashMap.put("admin",userO);
        System.out.println("加密后的admin密码为；"+pwd);

        //        存入第二个对象
        UserO userO1 = new UserO();
        //        将密码加密
        String pwd1 = bCryptPasswordEncoder.encode("123123");
        userO1.setUsername("zs");
        userO1.setPassword(pwd1);
        hashMap.put("zs",userO1);
        System.out.println("加密后的zs密码为；"+pwd1);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//        根据用户输入的用户名先查询伪数据库中是否存在记录
        UserO userO = hashMap.get(username);
        System.out.println("userO" + userO);
//        如果没有记录 直接返回Null
        if(userO==null){
            return null;
        }
//        获得数据库对象的用户名和密码
        String DBusername = userO.getUsername();
        String DBpassword = userO.getPassword();
//        获得数据库对象的权限 存取到集合中 (伪造数据)
        ArrayList<GrantedAuthority> Authorities = new ArrayList<>();
        Authorities.add(new SimpleGrantedAuthority("ROLE_admin"));
        Authorities.add(new SimpleGrantedAuthority("add"));
        Authorities.add(new SimpleGrantedAuthority("update"));
        System.out.println("SimpleGrantedAuthority:" + new SimpleGrantedAuthority("del"));
//        封装用户名密码和权限集到spring-security提供的对象中 返回给spring-security
//        User user = new User(DBusername, "{noop}"+DBpassword, Authorities);明文密码不加noop会报错！！
//        异常信息：们来看一下官方文档:
        User user = new User(DBusername, DBpassword, Authorities);
        System.out.println("user" + user);
        return user;
    }



}
